﻿using DevExpress.Printing;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using MesProjectWinform.Entity.Request;
using MesProjectWinform.Helper;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using MesProjectWinform.WareHouse.Entity;
using MesProjectWinform.WareHouse.Entity.Dto.Input;
using MesProjectWinform.WareHouse.Helper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using System.Xml.Linq;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace MesProjectWinform.WareHouse.Form.工序排序
{
    public partial class Form_ProcessAdd : DevExpress.XtraEditors.XtraForm
    {
        // 存储已选择的文件路径列表
        private List<string> selectedFiles = new List<string>();
        
        // 存储已添加的工序列表
        public List<ProcessItemModel> processItemList = new List<ProcessItemModel>();
        public List<ProcessFileModel> processFileList = new List<ProcessFileModel>();
        public Form_ProcessAdd()
        {
            InitializeComponent();
        }

        public bool UpdateType = false;
        public bool IsViewMode = false; // 添加查看模式标志

        // 使用ProcessclassModel类来接收数据
        public ProcessModel Current { get; set; }
        string depId = string.Empty;
        private async void Form_ProcessAdd_Load(object sender, EventArgs e)
        {
            try
            {
                // 显示等待光标
                Cursor = Cursors.WaitCursor;
                textEdit1.Text = "生产部";
                depId = "D25070400002";
                lookUpEmpType();
                if (UpdateType)
                {
                    // 新增模式
                    this.Text = "新增";
                    BtnAdd.Text = "新增";

                    // 直接异步获取编码并设置到文本框
                    string code = await GetCode(CodeType.Process);
                    txtPRId.Text = code;
                   
                    //启用状态默认为是
                    //toggleIsEnable.IsOn = true;
                }
                else
                {
                    // 新增模式
                    this.Text = "修改";
                    BtnAdd.Text = "修改";

                    // 绑定传入的数据到控件
                    if (Current != null)
                    {
                        // 填充表单控件
                        txtPRId.Text = Current.PRId;
                        txtPRName.Text = Current.PRName;
                        lookUpEMP.EditValue = Current.EmpId;
                        txtMemo.Text = Current.Memo;
                        //toggleIsEnable.IsOn = Current.IsEnable;

                    }
                }
                
                // 初始化文件列表视图
                InitializeFileListView();
                
                // 初始化工序列表数据源
                InitProcessGridControl();
                
                // 处理查看模式
                if (IsViewMode)
                {
                    // 设置窗体标题
                    this.Text = "查看工艺流程";
                    // 隐藏或禁用编辑按钮
                    BtnAdd.Visible = false;
                    BtnAddItem.Enabled = false;
                    btnBrowseFile.Enabled = false;
                    btnRemoveFile.Enabled = false;
                    
                    // 设置所有输入控件为只读
                    txtPRId.ReadOnly = true;
                    txtPRName.ReadOnly = true;
                    txtMemo.ReadOnly = true;
                    lookUpEMP.ReadOnly = true;
                    Btn_Down.Visible = true;
                    // 禁用工序项目表格的编辑功能（上移、下移、删除按钮）
                    gridView1.OptionsBehavior.Editable = false;
                    
                    // 更改关闭按钮的文本
                    BtnClose.Text = "关闭";
            }
                
                // 如果不是新增模式，且有传入工序项目和文件列表数据
                if (!UpdateType && processItemList != null && processItemList.Count > 0)
                {
                    // 绑定工序项目数据到gridControl1
                    gridControl1.DataSource = processItemList;
                    gridControl1.RefreshDataSource();
                }
                
                // 如果有文件列表数据，则显示文件列表
                if (processFileList != null && processFileList.Count > 0)
                {
                    // 显示文件列表
                    foreach (ProcessFileModel file in processFileList)
                    {
                        // 创建ListViewItem
                        ListViewItem item = new ListViewItem(file.PRFName);
                        // 文件大小字段暂不可获取，设置为空
                        item.SubItems.Add("-");
                        // 尝试获取文件扩展名
                        string extension = Path.GetExtension(file.PRFName);
                        item.SubItems.Add(extension);
                        // 创建时间
                        item.SubItems.Add(file.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        // 文件地址
                        item.SubItems.Add(file.Address);
                        // 添加URL作为标签
                        item.Tag = file.Address;
                        // 添加到列表视图
                        fileListView.Items.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载窗体时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }


        /// <summary>
        /// 下拉框类型人员填充
        /// </summary>
        public async void lookUpEmpType()
        {
            HttpClientHelper helper = new HttpClientHelper();
            string action = $"WareHouse/BasicInfo/GetEMP?DepId=D25070400002";
            string json = helper.RequestUrlNew(RequestType.Get, action, null);

            ApiResult<List<EMP>> TypeModel = JsonConvert.DeserializeObject<ApiResult<List<EMP>>>(json);

            if (TypeModel != null && TypeModel.Code == ApiEnums.Success && TypeModel.Data != null)
            {

                lookUpEMP.Properties.ValueMember = "EMPID";
                lookUpEMP.Properties.DisplayMember = "EMPName";
                lookUpEMP.Properties.DataSource = TypeModel.Data;
                // 设置列显示
                lookUpEMP.Properties.Columns.Clear();
                lookUpEMP.Properties.Columns.Add(new LookUpColumnInfo("EMPID", "编码"));
                lookUpEMP.Properties.Columns.Add(new LookUpColumnInfo("EMPName", "名称"));
                lookUpEMP.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
                
            }
        }

        /// <summary>
        /// 初始化工序列表数据源
        /// </summary>
        private void InitProcessGridControl()
        {
            // 创建一个空的数据源并绑定到gridControl1
            gridControl1.DataSource = processItemList;
        }

        /// <summary>
        /// 初始化文件列表视图
        /// </summary>
        private void InitializeFileListView()
        {
            // 添加列
            fileListView.Columns.Add("文件名", 350);
            fileListView.Columns.Add("文件大小", 150);
            fileListView.Columns.Add("文件类型", 150);
            fileListView.Columns.Add("上传时间", 200);
            fileListView.Columns.Add("文件路径", 400);
            
            // 启用全行选择
            fileListView.FullRowSelect = true;
        }

        /// <summary>
        /// 浏览文件按钮点击事件
        /// </summary>
        private void btnBrowseFile_Click(object sender, EventArgs e)
        {
            try
            {
                using (OpenFileDialog openFileDialog = new OpenFileDialog())
                {
                    openFileDialog.Multiselect = true;
                    openFileDialog.Filter = "所有文件|*.*";
                    openFileDialog.Title = "选择文件";

                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        // 显示等待光标
                        Cursor = Cursors.WaitCursor;

                        foreach (string filePath in openFileDialog.FileNames)
                        {
                            if (!selectedFiles.Contains(filePath))
                            {
                                // 上传文件到七牛云
                                string qiniuUrl = UploadFileToQiniu(filePath);

                                if (!string.IsNullOrEmpty(qiniuUrl))
                                {
                                    // 添加到列表视图
                                    AddFileToListView(filePath, qiniuUrl);
                                selectedFiles.Add(filePath);

                                    // 显示上传成功消息
                                    System.Diagnostics.Debug.WriteLine($"文件 {Path.GetFileName(filePath)} 上传成功: {qiniuUrl}");
                            }
                                else
                                {
                                    MessageBox.Show($"文件 {Path.GetFileName(filePath)} 上传失败", "上传失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }

                        // 恢复光标
                        Cursor = Cursors.Default;
            }
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("选择文件时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 上传文件到七牛云
        /// </summary>
        /// <param name="filePath">本地文件路径</param>
        /// <returns>上传成功后的URL，失败则返回空字符串</returns>
        private string UploadFileToQiniu(string filePath)
        {
            try
            {
                // 获取文件名作为上传后的文件名
                string fileName = Path.GetFileName(filePath);

                // 使用QiNiuHelper上传文件
                return QiNiuHelper.UploadFile(filePath, fileName);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"上传文件到七牛云时发生错误: {ex.Message}");
                return string.Empty;
            }
        }

        /// <summary>
        /// 添加文件到列表视图
        /// </summary>
        private void AddFileToListView(string filePath, string qiniuUrl = "")
        {
            try
            {
                FileInfo fileInfo = new FileInfo(filePath);
                
                ListViewItem item = new ListViewItem(fileInfo.Name);
                item.SubItems.Add(FormatFileSize(fileInfo.Length));
                item.SubItems.Add(fileInfo.Extension);
                item.SubItems.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                item.SubItems.Add(qiniuUrl);
                
                // 添加七牛云URL作为标签
                item.Tag = qiniuUrl;

                fileListView.Items.Add(item);

                ProcessFileModel model = new ProcessFileModel();
                model.Address = qiniuUrl;
                model.PRId = txtPRId.Text.Trim();
                model.PRFName = fileInfo.Name;
                model.PRFId = "0";
                //model.Url = filePath;
                model.CreateTime = DateTime.Now;
                processFileList.Add(model);

            }
            catch (Exception ex)
            {
                MessageBox.Show("添加文件到列表时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        private string FormatFileSize(long byteCount)
        {
            string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
            if (byteCount == 0)
                return "0" + suf[0];
            
            long bytes = Math.Abs(byteCount);
            int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            double num = Math.Round(bytes / Math.Pow(1024, place), 1);
            return $"{(Math.Sign(byteCount) * num).ToString("0.##")} {suf[place]}";
        }

        /// <summary>
        /// 删除文件按钮点击事件
        /// </summary>
        private void btnRemoveFile_Click(object sender, EventArgs e)
        {
            try
            {
                if (fileListView.SelectedItems.Count > 0)
                {
                    // 使用ToList()创建一个副本以避免集合修改异常
                    List<ListViewItem> selectedItemsList = new List<ListViewItem>();
                    foreach (ListViewItem item in fileListView.SelectedItems)
                    {
                        selectedItemsList.Add(item);
                    }

                    foreach (ListViewItem item in selectedItemsList)
                    {
                        // 获取本地文件路径
                        string filePath = item.SubItems[4].Text;

                        // 获取七牛云URL（存储在Tag属性中）
                        string qiniuUrl = item.Tag?.ToString() ?? string.Empty;

                        // 如果七牛云URL不为空，尝试从七牛云删除文件
                        if (!string.IsNullOrEmpty(qiniuUrl))
                        {
                            bool deleteResult = QiNiuHelper.DeleteFile(qiniuUrl);
                            if (deleteResult)
                            {
                                System.Diagnostics.Debug.WriteLine($"已成功从七牛云删除文件: {qiniuUrl}");
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine($"从七牛云删除文件失败: {qiniuUrl}");
                                // 如果删除失败，仍然继续处理本地引用的删除
                            }

                            // 同时从processFileList中移除
                            ProcessFileModel fileToRemove = processFileList.FirstOrDefault(f => f.Address == qiniuUrl);
                            if (fileToRemove != null)
                            {
                                processFileList.Remove(fileToRemove);
                            }
                        }

                        // 从selectedFiles列表中移除
                        selectedFiles.Remove(filePath);

                        // 从ListView控件中移除
                        fileListView.Items.Remove(item);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要删除的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除文件时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 获取已选择的文件列表
        /// </summary>
        public List<string> GetSelectedFiles()
        {
            return selectedFiles;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BtnAdd_Click(object sender, EventArgs e)
        {
            string requestId = Guid.NewGuid().ToString();
            ProcessInput Input = new ProcessInput();

            Input.ProcessItem = processItemList.ToList();
            Input.ProcessFile = processFileList.ToList();

            ProcessModel Processmodel = new ProcessModel();
            Processmodel.PRId = txtPRId.Text.ToString();
            Processmodel.PRName = txtPRName.Text.ToString();
            Processmodel.PRNum = processItemList.Count();
            Processmodel.DepName = textEdit1.Text.Trim();
            Processmodel.DepId = depId;
            Processmodel.EmpId = lookUpEMP.EditValue.ToString();
            Processmodel.Memo = txtMemo.Text.Trim();
            Input.Process = Processmodel;

            // 将对象序列化为JSON
            string postData = JsonConvert.SerializeObject(Input);

            // 添加请求ID，用于防止重复提交
            Dictionary<string, string> headers = new Dictionary<string, string>
                {
                    { "X-Request-ID", requestId },
                    { "X-Client-Timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") }
                };

            int maxRetries = 3;
            int retryCount = 0;
            bool success = false;

            while (!success && retryCount < maxRetries)
            {
                try
                {
                    HttpClientHelper helper = new HttpClientHelper();
                    // 根据操作类型选择API
                    string url = UpdateType ?"WareHouse/Process/AddProcess": "WareHouse/Process/UpdateProcess";

                    // 使用带自定义头的请求方法
                     string json = helper.RequestUrlNew(RequestType.Post, url, postData);
                    ApiResult<bool> baseModel = JsonConvert.DeserializeObject<ApiResult<bool>>(json);

                    if (baseModel.Code == ApiEnums.Success)
                    {
                        // 更新编码记录
                        await UpdateCode();

                        string message = UpdateType ? "添加成功" : "修改成功";
                        MessageBox.Show(message, "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.DialogResult = DialogResult.OK;

                        // 标记成功
                        success = true;

                        // 关闭窗口
                        this.Close();
        }
                    else
                    {
                        // 检查是否是因为并发冲突导致的失败
                        if (baseModel.Code == ApiEnums.Error)
                        {
                            retryCount++;
                            if (retryCount < maxRetries)
                            {
                                // 等待一段时间后重试
                                await Task.Delay(1000 * retryCount); // 逐次增加等待时间
                                continue;
                            }
                        }

                        MessageBox.Show(baseModel.Message, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    retryCount++;
                    if (retryCount >= maxRetries)
                    {
                        MessageBox.Show("保存数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        break;
                    }

                    // 等待一段时间后重试
                    await Task.Delay(1000 * retryCount);
                }
            }

        }
        

        /// <summary>
        /// 添加工序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddItem_Click(object sender, EventArgs e)
        {
            try
            {
                Form_ProcessItem from = new Form_ProcessItem();
                // 注册选择完成事件
                from.OnProcessSelected += From_OnProcessSelected;

                // 注册窗体关闭事件，用于取消订阅
                from.FormClosed += (s, args) =>
                {
                    // 窗体关闭时取消订阅事件，防止内存泄漏
                    ((Form_ProcessItem)s).OnProcessSelected -= From_OnProcessSelected;
                };

                from.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show("添加工序时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 处理工序选择完成事件
        /// </summary>
        /// <param name="processes">选择的工序列表</param>
        private void From_OnProcessSelected(List<ProcessItemModel> processes)
        {
            try
            {
                if (processes != null && processes.Count > 0)
                {
                    // 为每个新添加的工序设置序号
                    foreach (var process in processes)
                    {
                        // 检查是否已经存在相同ID的工序
                        bool exists = processItemList.Any(p => p.PMId == process.PMId);
                        
                        // 如果不存在，则添加
                        if (!exists)
                        {
                            // 设置PNum值为当前列表中的最大序号+1
                            int maxPNum = 0;
                            if (processItemList.Count > 0)
                            {
                                maxPNum = processItemList.Max(p => p.PNum);
                            }
                            process.PNum = maxPNum + 1;
                            process.PRId = txtPRId.Text.Trim();
                            process.PId = "0";
                            // 添加到列表
                            processItemList.Add(process);
                        }
                    }
                    
                    // 重新排序并刷新数据源
                    RefreshGridControl();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("处理选择的工序数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新工序列表控件
        /// </summary>
        //private void RefreshGridControl()
        //{
        //    // 按PNum排序
        //    var sortedList = processManagList.OrderBy(p => p.PNum).ToList();
        //    processManagList = sortedList;

        //    // 更新数据源
        //    gridControl1.DataSource = null;
        //    gridControl1.DataSource = processManagList;
        //    gridControl1.RefreshDataSource();
        //}

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClose_Click(object sender, EventArgs e)
        {
            if (processFileList.Count > 0)
            {
                try
                {
                    // 显示等待光标
                    Cursor = Cursors.WaitCursor;

                    // 创建副本以避免在遍历过程中修改集合
                    List<ProcessFileModel> filesToDelete = new List<ProcessFileModel>(processFileList);

                    foreach (var file in filesToDelete)
                    {
                        if (!string.IsNullOrEmpty(file.Address))
                        {
                            // 从七牛云删除文件
                            bool deleteResult = QiNiuHelper.DeleteFile(file.Address);
                            //if (deleteResult)
                            //{
                            //    System.Diagnostics.Debug.WriteLine($"已成功从七牛云删除文件: {file.Address}");
                            //}
                            //else
                            //{
                            //    System.Diagnostics.Debug.WriteLine($"从七牛云删除文件失败: {file.Address}");
                            //}
                        }
                    }

                    // 清空文件列表
                    processFileList.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("删除上传文件时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    // 恢复光标
                    Cursor = Cursors.Default;
                }
            }

            DialogResult = DialogResult.Cancel;
            Close();
        }

        /// <summary>
        /// 下拉框值变动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lookUpEMP_EditValueChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 上移
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Up_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行索引
                int rowHandle = gridView1.FocusedRowHandle;
                if (rowHandle <= 0) return; // 已经是第一行，不能再上移

                // 获取选中的工序和上一个工序
                ProcessItemModel currentProcess = gridView1.GetRow(rowHandle) as ProcessItemModel;
                ProcessItemModel prevProcess = gridView1.GetRow(rowHandle - 1) as ProcessItemModel;
                
                if (currentProcess != null && prevProcess != null)
                {
                    // 交换PNum值
                    int temp = currentProcess.PNum;
                    currentProcess.PNum = prevProcess.PNum;
                    prevProcess.PNum = temp;
                    
                    // 刷新数据源
                    RefreshGridControl();
                    
                    // 选中交换后的行
                    gridView1.FocusedRowHandle = rowHandle - 1;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("上移工序时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 下移
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Down_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行索引和总行数
                int rowHandle = gridView1.FocusedRowHandle;
                int rowCount = gridView1.RowCount;
                
                if (rowHandle >= rowCount - 1) return; // 已经是最后一行，不能再下移

                // 获取选中的工序和下一个工序
                ProcessItemModel currentProcess = gridView1.GetRow(rowHandle) as ProcessItemModel;
                ProcessItemModel nextProcess = gridView1.GetRow(rowHandle + 1) as ProcessItemModel;
                
                if (currentProcess != null && nextProcess != null)
                {
                    // 交换PNum值
                    int temp = currentProcess.PNum;
                    currentProcess.PNum = nextProcess.PNum;
                    nextProcess.PNum = temp;
                    
                    // 刷新数据源
                    RefreshGridControl();
                    
                    // 选中交换后的行
                    gridView1.FocusedRowHandle = rowHandle + 1;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("下移工序时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Delete_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行索引
                int rowHandle = gridView1.FocusedRowHandle;
                if (rowHandle < 0) return;

                // 获取选中的工序
                ProcessItemModel selectedProcess = gridView1.GetRow(rowHandle) as ProcessItemModel;
                
                if (selectedProcess != null)
                {
                    // 从列表中移除
                    processItemList.Remove(selectedProcess);
                    
                    // 重新排序PNum
                    for (int i = 0; i < processItemList.Count; i++)
                    {
                        processItemList[i].PNum = i + 1;
                    }
                    
                    // 刷新数据源
                    RefreshGridControl();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除工序时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        #region 自定义方法
        ///// <summary>
        ///// 检查必填字段
        ///// </summary>
        //private string Check()
        //{
        //    List<string> emptyFields = new List<string>();

        //    // 检查编号
        //    if (string.IsNullOrWhiteSpace(txtCode.Text))
        //    {
        //        emptyFields.Add("编码");
        //    }

        //    // 检查名称
        //    if (string.IsNullOrWhiteSpace(txtName.Text))
        //    {
        //        emptyFields.Add("名称");
        //    }


        //    // 如果有空字段，返回错误消息
        //    if (emptyFields.Count > 0)
        //    {
        //        return $"添加失败，以下字段不能为空：{string.Join("、", emptyFields)}";
        //    }

        //    // 所有字段都已填写
        //    return string.Empty;
        //}

        /// <summary>
        /// 刷新工序列表控件
        /// </summary>
        private void RefreshGridControl()
        {
            try
            {
                // 按PNum排序
                var sortedList = processItemList.OrderBy(p => p.PNum).ToList();
                processItemList = sortedList;

                // 更新数据源
                gridControl1.DataSource = null;
                gridControl1.DataSource = processItemList;

                // 刷新网格视图
                gridView1.RefreshData();
                gridControl1.RefreshDataSource();

                // 强制重绘
                gridControl1.Refresh();

                // 如果有数据，尝试选中第一行
                if (processItemList.Count > 0)
                {
                    gridView1.FocusedRowHandle = 0;
                }

                // 记录日志，用于调试
                System.Diagnostics.Debug.WriteLine($"已刷新工序列表，共{processItemList.Count}条记录");
            }
            catch (Exception ex)
            {
                MessageBox.Show("刷新工序列表时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // <summary>
        /// 更新编码记录
        /// </summary>
        public async Task UpdateCode(CodeType codeType, string name)
        {
            try
            {
                HttpClientHelper helper = new HttpClientHelper();
                // 根据操作类型选择API
                string url = "WareHouse/BasicInfo/UpdateCode";
                TypeCodeModel model = new TypeCodeModel();
                model.Code = txtPRId.Text;
                model.CodeType = DataConverHelper.GetPrefix(codeType);
                model.CodeTypeName = name;
                string postData = JsonConvert.SerializeObject(model);

                // 设置重试次数
                int maxRetries = 3;
                int retryCount = 0;
                bool success = false;

                while (!success && retryCount < maxRetries)
                {
                    try
                    {
                        string json = helper.RequestUrlNew(RequestType.Put, url, postData);
                        ApiResult<int> baseModel = JsonConvert.DeserializeObject<ApiResult<int>>(json);

                        if (baseModel != null && baseModel.Code == ApiEnums.Success)
                        {
                            success = true;
                            return;
                        }

                        // 如果失败，尝试重试
                        retryCount++;
                        if (retryCount < maxRetries)
                        {
                            await Task.Delay(1000 * retryCount);
                        }
                    }
                    catch (Exception ex)
                    {
                        //System.Diagnostics.Debug.WriteLine($"更新编码记录时发生异常: {ex.Message}");
                        retryCount++;
                        if (retryCount < maxRetries)
                        {
                            await Task.Delay(1000 * retryCount);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //System.Diagnostics.Debug.WriteLine($"更新编码记录失败: {ex.Message}");
                // 这里选择不抛出异常，因为即使编码记录更新失败，主业务流程已经完成
            }
        }

        /// <summary>
        /// 获取标签编码
        /// </summary>
        private async Task<string> GetCode(CodeType codeType)
        {
            try
            {
                // 显示等待光标
                Cursor = Cursors.WaitCursor;

                string codePrefix = DataConverHelper.GetPrefix(codeType);

                // 首先尝试直接生成一个新编码作为备选
                string fallbackCode = DataConverHelper.GenerateCode(codeType);

                // 获取互联网时间
                //DateTime internetTime = await GetInternetTime();
                ////System.Diagnostics.Debug.WriteLine($"互联网时间: {internetTime}，本地时间: {DateTime.Now}");

                try
                {
                    // 调用API获取最新编码
                    string apiUrl = "WareHouse/BasicInfo/GetCode?Type=" + codePrefix;
                    HttpClientHelper helper = new HttpClientHelper();
                    string json = helper.RequestUrlNew(RequestType.Get, apiUrl, null);

                    if (string.IsNullOrEmpty(json))
                    {
                        return fallbackCode;
                    }

                    ApiResult<TypeCodeModel> typeModel = JsonConvert.DeserializeObject<ApiResult<TypeCodeModel>>(json);

                    if (typeModel == null || typeModel.Data == null)
                    {
                        return fallbackCode;
                    }

                    string lastCode = typeModel.Data.Code;

                    if (string.IsNullOrEmpty(lastCode))
                    {
                        return fallbackCode;
                    }

                    // 获取数字部分（后五位或全部，如果不足五位）
                    string numberPart;
                    string prefixPart;

                    // 提取数字部分和前缀部分
                    if (lastCode.Length >= 5)
                    {
                        // 如果编码长度超过5位，提取最后5位作为数字部分，其余作为前缀
                        numberPart = lastCode.Substring(lastCode.Length - 5);
                        prefixPart = lastCode.Substring(0, lastCode.Length - 5);
                    }
                    else
                    {
                        // 如果编码长度不足5位，就用整个编码作为数字部分，前缀为空
                        numberPart = lastCode;
                        prefixPart = "";
                    }

                    // 尝试解析为数字并自增1
                    if (int.TryParse(numberPart, out int lastNumber))
                    {
                        // 使用互联网时间获取当前日期字符串
                        string currentDateStr = DateTime.Now.ToString("yyMMdd");
                        string dateInPrefix = "";

                        // 检查前缀中是否包含日期信息
                        if (prefixPart.Length >= 8 && prefixPart.StartsWith(codePrefix))
                        {
                            dateInPrefix = prefixPart.Substring(2, 6);
                        }

                        // 如果前缀中的日期与当前日期不同，或者前缀不合规范，则重置编号并使用新日期
                        if (string.IsNullOrEmpty(prefixPart) || !prefixPart.StartsWith(codePrefix) ||
                            (dateInPrefix != currentDateStr && !string.IsNullOrEmpty(dateInPrefix)))
                        {
                            // 新的一天，编号从1开始
                            prefixPart = codePrefix + currentDateStr;
                            lastNumber = 1; // 重置为1
                        }
                        else
                        {
                            // 同一天，编号递增
                            lastNumber++;
                        }

                        // 数字部分解析成功，确保是5位数（前面补0）
                        string fiveDigitNumber = lastNumber.ToString("D5");

                        // 组合新编码
                        string newCode = prefixPart + fiveDigitNumber;
                        return newCode;
                    }
                    else
                    {
                        return fallbackCode;
                    }
                }
                catch (Exception ex)
                {
                    //System.Diagnostics.Debug.WriteLine($"获取编码异常: {ex.Message}");
                    return fallbackCode;
                }
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 更新编码记录
        /// </summary>
        public async Task UpdateCode()
        {
            try
            {
                // 根据操作类型选择API
                string url = "WareHouse/BasicInfo/UpdateCode";
                TypeCodeModel model = new TypeCodeModel();
                model.Code = txtPRId.Text;
                model.CodeType = DataConverHelper.GetPrefix(CodeType.Process);
                model.CodeTypeName = "工艺";
                string postData = JsonConvert.SerializeObject(model);

                // 设置重试次数
                int maxRetries = 3;
                int retryCount = 0;
                bool success = false;

                while (!success && retryCount < maxRetries)
                {
                    try
                    {
                        HttpClientHelper helper = new HttpClientHelper();
                        string json = helper.RequestUrlNew(RequestType.Put, url, postData);
                        ApiResult<int> baseModel = JsonConvert.DeserializeObject<ApiResult<int>>(json);

                        if (baseModel != null && baseModel.Code == ApiEnums.Success)
                        {
                            success = true;
                            return;
                        }

                        // 如果失败，尝试重试
                        retryCount++;
                        if (retryCount < maxRetries)
                        {
                            await Task.Delay(1000 * retryCount);
                        }
                    }
                    catch (Exception ex)
                    {
                        //System.Diagnostics.Debug.WriteLine($"更新编码记录时发生异常: {ex.Message}");
                        retryCount++;
                        if (retryCount < maxRetries)
                        {
                            await Task.Delay(1000 * retryCount);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //System.Diagnostics.Debug.WriteLine($"更新编码记录失败: {ex.Message}");
                // 这里选择不抛出异常，因为即使编码记录更新失败，主业务流程已经完成
            }
        }

        #endregion

        /// <summary>
        /// 下载文档
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Down_Click(object sender, EventArgs e)
        {
            try
            {
                if (fileListView.SelectedItems.Count > 0)
                {
                    // 显示等待光标
                    Cursor = Cursors.WaitCursor;

                    // 创建文件保存对话框
                    using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
                    {
                        folderDialog.Description = "请选择下载文件的保存位置";
                        folderDialog.ShowNewFolderButton = true;

                        if (folderDialog.ShowDialog() == DialogResult.OK)
                        {
                            string saveDirectory = folderDialog.SelectedPath;
                            int successCount = 0;
                            int failCount = 0;

                            // 处理选中的每个文件
                            foreach (ListViewItem item in fileListView.SelectedItems)
                            {
                                // 获取文件名
                                string fileName = item.Text;
                                
                                // 获取七牛云URL（存储在Tag属性中）
                                string qiniuUrl = item.Tag?.ToString() ?? string.Empty;

                                if (!string.IsNullOrEmpty(qiniuUrl))
                                {
                                    // 构建本地保存路径
                                    string localFilePath = Path.Combine(saveDirectory, fileName);
                                    
                                    // 调用QiNiuHelper下载文件（从私有空间下载）
                                    bool downloadResult = QiNiuHelper.DownloadFile(qiniuUrl, localFilePath, fileName,false);

                                    if (downloadResult)
                                    {
                                        successCount++;
                                        //System.Diagnostics.Debug.WriteLine($"文件下载成功: {fileName}");
                                    }
                                    else
                                    {
                                        failCount++;
                                        //System.Diagnostics.Debug.WriteLine($"文件下载失败: {fileName}");
                                    }
                                }
                            }

                            // 显示下载结果
                            if (successCount > 0 && failCount == 0)
                            {
                                MessageBox.Show($"成功下载 {successCount} 个文件", "下载完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else if (successCount > 0 && failCount > 0)
                            {
                                MessageBox.Show($"成功下载 {successCount} 个文件，{failCount} 个文件下载失败", "下载部分完成", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                            else
                            {
                                MessageBox.Show("所有文件下载失败", "下载失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要下载的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("下载文件时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
    }
}